//
//  THFlowEarnTaskHallVC.m
//  YJB
//
//  Created by 中电大维 on 2017/1/12.
//  Copyright © 2017年 YJB. All rights reserved.
//

#import "THFlowEarnTaskHallVC.h"
#import "THFlowEarnHallCell.h"
#import "THFlowEarnHallModel.h"
#import "THPublisherModel.h"
#import "THFlowEarnReportVC.h"
#import "THFlowEarnCurrentTaskDetailVC.h"
#import "THReportView.h"

typedef enum {
    FlowEarnTypeAll = 0,
    FlowEarnTypePriceUp,
    FlowEarnTypePriceDown,
    FlowEarnTypePubliser
} FlowEarnTypeState;
@interface THFlowEarnTaskHallVC ()<UIGestureRecognizerDelegate,UIScrollViewDelegate,THReportDelegate>
@property (nonatomic, strong)UIButton *allTask;
@property (nonatomic, strong)UIButton *priceTask;
@property (nonatomic, strong)UIButton *publisherTask;
@property (nonatomic, strong)UITableView *menuTableView;
@property (nonatomic, strong)UIButton *background;
@property (nonatomic, strong)NSMutableArray *tasks;
@property (nonatomic, strong)NSMutableArray *publishers;
@property (nonatomic, strong)THReportView *reportView;
@end

@implementation THFlowEarnTaskHallVC
{
    NSInteger _selectRow;
    NSInteger _selectPublisherRow;
    THFlowEarnReportVC *_controller;
    THFlowEarnHallModel *_model;
    FlowEarnTypeState _typeState;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.background.hidden == NO) {
        [self setHiddenListView:YES];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"eeeeee"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.mj_header beginRefreshing];
    [self.tableView registerClass:[THFlowEarnHallCell class] forCellReuseIdentifier:flowEarnHallCellID];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.tableView setSeparatorColor:[UIColor colorWithHexString:@"e5e5e5"]];
    
    UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPressGR.minimumPressDuration = 1.0;
    [self.tableView addGestureRecognizer:longPressGR];
    
    [self.view addSubview:self.background];
    [self.view addSubview:self.menuTableView];
    _controller = [[THFlowEarnReportVC alloc] init];
    _model = [[THFlowEarnHallModel alloc] init];
    _typeState = FlowEarnTypeAll;
    _selectRow = 0;
    _selectPublisherRow = 0;
    [self loadPublisherData];
}

-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan) {
        
        if (!self.menuTableView.hidden) {
            return;
        }
        self.reportView.hidden = NO;
        CGPoint point = [gesture locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
        _model = self.tasks[indexPath.row];
        _controller.reportType = 1;
        _controller.reportTitle = _model.sitename;
        _controller.reportID = _model.ID;
    }
}

- (void)pushReportController
{
    [self.navigationController pushViewController:_controller animated:YES];
}

- (void)loadData
{
    [self.tasks removeAllObjects];
#pragma mark - 全部的列表
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userName = [YJUserDefaultTool readUserName];
    NSString *md5Key = [YJUserDefaultTool readKeyID];
    NSString *url = THURL(@"manual.php");
    switch (_typeState) {
        case FlowEarnTypeAll:
        {
            params[@"action"] = @"get_all_list";
            params[@"makegold"] = @{@"username":userName,
                                    @"firstrow":@"-1",
                                    @"listrows":@"",
                                    @"user_info":userName,
                                    @"phone_info":@"iOS",
                                    @"md5_key":md5Key};
        }
            break;
        case FlowEarnTypePriceUp://从低到高
        {
            params[@"action"] = @"get_again_sort";
            params[@"makegold"] = @{@"username":userName,
                                    @"type":@"1",
                                    @"key":@"2",
                                    @"firstrow":@"-1",
                                    @"listrows":@"",
                                    @"user_info":userName,
                                    @"phone_info":@"iOS",
                                    @"md5_key":md5Key};
        }
            break;
        case FlowEarnTypePriceDown://从高到低
        {
            params[@"action"] = @"get_again_sort";
            params[@"makegold"] = @{@"username":userName,
                                    @"type":@"1",
                                    @"key":@"1",
                                    @"firstrow":@"-1",
                                    @"listrows":@"",
                                    @"user_info":userName,
                                    @"phone_info":@"iOS",
                                    @"md5_key":md5Key};
        }
            break;
        case FlowEarnTypePubliser:
        {
            THPublisherModel *model = self.publishers[_selectPublisherRow];
            params[@"action"] = @"get_again_sort";
            params[@"makegold"] = @{@"username":userName,
                                    @"type":@"2",
                                    @"key":model.userid,
                                    @"firstrow":@"-1",
                                    @"listrows":@"",
                                    @"user_info":userName,
                                    @"phone_info":@"iOS",
                                    @"md5_key":md5Key};
        }
            break;
    }
    [YJNetworkTool postWithUrl:url parameters:params success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        NSString *code = responseObject[@"return"][@"code"];
        if (code.integerValue == 200)
        {
            NSArray *array = responseObject[@"return"][@"data"][@"list"];
            self.tasks = [THFlowEarnHallModel mj_objectArrayWithKeyValuesArray:array];
        }
        else if(code.integerValue == 500)
            [self.tasks removeAllObjects];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
    }];
}

- (void)loadPublisherData
{
#pragma mark - 全部的列表
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userName = [YJUserDefaultTool readUserName];
    NSString *md5Key = [YJUserDefaultTool readKeyID];
    NSString *url = [[NSString alloc] init];
    params[@"action"] = @"get_publisher_list";
    url = THURL(@"manual.php");
    params[@"makegold"] = @{@"firstrow":@"-1",
                            @"listrows":@"",
                            @"user_info":userName,
                            @"phone_info":@"iOS",
                            @"md5_key":md5Key};
    [YJNetworkTool postWithUrl:url parameters:params success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        NSString *code = responseObject[@"return"][@"code"];
        if (code.integerValue == 200)
        {
            NSArray *array = responseObject[@"return"][@"data"][@"list"];
            self.publishers = [THPublisherModel mj_objectArrayWithKeyValuesArray:array];
        }else{
            [self loadPublisherData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
        [self loadPublisherData];
    }];
}

- (void)allTaskClick:(UIButton *)button
{
    if (button.selected) {
        return;
    }
    _typeState = FlowEarnTypeAll;
    [self.tableView.header beginRefreshing];
    [self setlineColor:button];
}
- (void)priceTaskClick:(UIButton *)button
{
    switch (_selectRow) {
        case 0:
            _typeState = FlowEarnTypePriceUp;
            break;
            
        case 1:
            _typeState = FlowEarnTypePriceDown;
            break;
    }
    [self setlineColor:button];
}

- (void)publisherTaskClick:(UIButton *)button
{
    _typeState = FlowEarnTypePubliser;
    [self setlineColor:button];
}

- (void)setHiddenListView:(BOOL)hidden
{
    [self.menuTableView reloadData];
    
    if (hidden) {
        [self.publisherTask setImage:Image(@"triangle_down") forState:UIControlStateNormal];
        [self.priceTask setImage:Image(@"triangle_down") forState:UIControlStateNormal];
    }
    
    self.background.hidden = hidden;
    self.menuTableView.hidden = hidden;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 100) {
        
        if (self.priceTask.selected) {
            return 2;
        }
        return self.publishers.count;
    }
    return self.tasks.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 100) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"priceID"];
        if (!cell) {
            cell = [[UITableViewCell alloc] init];
            cell.textLabel.textColor = [UIColor colorWithHexString:@"333333"];
            cell.textLabel.font = FONT(16);
            cell.tintColor = [UIColor colorWithHexString:@"ff783c"];
        }

        if (self.priceTask.selected) {
            NSArray *subs = [[NSArray alloc] initWithObjects:@"金币由低到高",@"金币由高到低", nil];
            cell.textLabel.text = subs[indexPath.row];
            if (_selectRow == indexPath.row) {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }else{
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
            return cell;
        }
        THPublisherModel *model = self.publishers[indexPath.row];
        cell.textLabel.text = model.username;
        if (_selectPublisherRow == indexPath.row) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }else{
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;
    }
    THFlowEarnHallCell *cell = [tableView dequeueReusableCellWithIdentifier:flowEarnHallCellID forIndexPath:indexPath];
    cell.model = self.tasks[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 100) {
        
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self setHiddenListView:YES];
        if (self.priceTask.selected) {
            if (indexPath.row) {
                _typeState = FlowEarnTypePriceDown;
            }else{
                _typeState = FlowEarnTypePriceUp;
            }
            [self.tableView.header beginRefreshing];
            _selectRow = indexPath.row;
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            return;
        }
        _selectPublisherRow = indexPath.row;
        [self.tableView.header beginRefreshing];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    
    THFlowEarnHallModel *model = self.tasks[indexPath.row];
    THFlowEarnCurrentTaskDetailVC *vc = [[THFlowEarnCurrentTaskDetailVC alloc] init];
    vc.title = @"手动赚钱";
    vc.url = model.url;
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 100) {
        return TextField_RowHeight;
    }else{

        THFlowEarnHallModel *model = self.tasks[indexPath.row];
        return model.cellHeight;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 100) {
        return 0;
    }
    return TextField_RowHeight;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 100) {
        return nil;
    }
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    [view addSubview:self.allTask];
    [view addSubview:self.priceTask];
    [view addSubview:self.publisherTask];

    [self.allTask mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(IPHONE_W*(1/3.0));
    }];
    [self.priceTask mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(0);
        make.left.equalTo(self.allTask.mas_right);
        make.width.equalTo(self.allTask.mas_width);
    }];
    [self.publisherTask mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.mas_equalTo(0);
        make.left.equalTo(self.priceTask.mas_right);
    }];
    
    return view;
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//    if (self.background.hidden == NO) {
//        [self setHiddenListView:YES];
//    }
}
- (void)setlineColor:(UIButton *)button
{
    
    UIView *allLine = [self.allTask viewWithTag:11];
    UIView *priceLine = [self.priceTask viewWithTag:11];
    UIView *publiserLine = [self.publisherTask viewWithTag:11];
    
    NSArray *buttons = @[self.allTask,self.priceTask,self.publisherTask];
    NSArray *lines = @[allLine,priceLine,publiserLine];

    switch (button.tag) {
        case 1:
        {
            [self setHiddenListView:YES];
        }
            break;
        case 2:
        {
            if (self.priceTask.selected&&!self.menuTableView.hidden) {//如果是刚刚选中的，就先隐藏listview
                [self setHiddenListView:YES];
                [self.tableView.mj_header beginRefreshing];
            }else{
                [self.priceTask setImage:Image(@"triangle_up") forState:UIControlStateNormal];
                [self.publisherTask setImage:Image(@"triangle_down") forState:UIControlStateNormal];
                self.allTask.selected = NO;
                self.priceTask.selected = YES;
                self.publisherTask.selected = NO;
                [self setHiddenListView:NO];
            }
        }
            break;
        case 3:
        {
            if (self.publisherTask.selected&&!self.menuTableView.hidden) {//如果是刚刚选中的，就先隐藏listview
                [self setHiddenListView:YES];
                [self.tableView.mj_header beginRefreshing];
            }else{
                [self.publisherTask setImage:Image(@"triangle_up") forState:UIControlStateNormal];
                [self.priceTask setImage:Image(@"triangle_down") forState:UIControlStateNormal];
                self.allTask.selected = NO;
                self.priceTask.selected = NO;
                self.publisherTask.selected = YES;
                [self setHiddenListView:NO];
            }
        }
            break;
    }
    
    for (int i = 0 ; i < buttons.count; i++) {
        UIButton *button = buttons[i];
        UIView *line = lines[i];
        button.selected = NO;
        line.backgroundColor = [UIColor colorWithHexString:@"cfcfcf"];
        [line mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0.5);
        }];
    }

    button.selected = YES;
    UIView *line = lines[button.tag-1];
    line.backgroundColor = [UIColor colorWithHexString:@"ff783c"];
    [line mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(1.5);
    }];
}
- (UITableView *)menuTableView
{
    if (!_menuTableView) {
        _menuTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, TextField_RowHeight, IPHONE_W, TextField_RowHeight*10)];
        _menuTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _menuTableView.delegate = self;
        _menuTableView.dataSource = self;
        _menuTableView.rowHeight = TextField_RowHeight;
        _menuTableView.hidden = YES;
        _menuTableView.tag = 100;
        _menuTableView.backgroundColor = [UIColor clearColor];
    }
    return _menuTableView;
}
- (UIButton *)allTask
{
    if (!_allTask) {
        _allTask = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, IPHONE_W/3.0, TextField_RowHeight)];
        _allTask.tag = 1;
        [_allTask setTitle:@"全部"  forState:UIControlStateNormal];
        [_allTask setTitleColor:[UIColor colorWithHexString:@"333333"] forState:UIControlStateNormal];
        [_allTask setTitleColor:[UIColor colorWithHexString:@"ff783c"] forState:UIControlStateSelected];
        [_allTask addTarget:self action:@selector(allTaskClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addline:_allTask];
        [self allTaskClick:_allTask];
    }
    return _allTask;
}
- (UIButton *)priceTask
{
    if (!_priceTask) {
        _priceTask = [[UIButton alloc] initWithFrame:CGRectMake(self.allTask.rightX, self.allTask.y, self.allTask.width, self.allTask.height)];
        _priceTask.tag = 2;
        [_priceTask setTitle:@"价格" forState:UIControlStateNormal];
        [_priceTask setTitleColor:[UIColor colorWithHexString:@"333333"] forState:UIControlStateNormal];
        [_priceTask setTitleColor:[UIColor colorWithHexString:@"ff783c"] forState:UIControlStateSelected];
        [_priceTask addTarget:self action:@selector(priceTaskClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addline:_priceTask];
        [_priceTask setTitleEdgeInsets:UIEdgeInsetsMake(0, -_priceTask.imageView.bounds.size.width, 0, _priceTask.titleLabel.bounds.size.width)];
        [_priceTask setImageEdgeInsets:UIEdgeInsetsMake(0, _priceTask.titleLabel.bounds.size.width+5, 0, -_priceTask.titleLabel.bounds.size.width)];
        [_priceTask setImage:Image(@"triangle_down") forState:UIControlStateNormal];
    }
    return _priceTask;
}
- (UIButton *)publisherTask
{
    if (!_publisherTask) {
        _publisherTask = [[UIButton alloc] initWithFrame:CGRectMake(self.priceTask.rightX, self.allTask.y, self.priceTask.width, self.priceTask.height)];
        _publisherTask.tag = 3;
        [_publisherTask setTitle:@"发布者" forState:UIControlStateNormal];
        [_publisherTask setTitleColor:[UIColor colorWithHexString:@"333333"] forState:UIControlStateNormal];
        [_publisherTask setTitleColor:[UIColor colorWithHexString:@"ff783c"] forState:UIControlStateSelected];
        [_publisherTask addTarget:self action:@selector(publisherTaskClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addline:_publisherTask];
        [_publisherTask setTitleEdgeInsets:UIEdgeInsetsMake(0, -_publisherTask.imageView.bounds.size.width, 0, _publisherTask.titleLabel.bounds.size.width)];
        [_publisherTask setImageEdgeInsets:UIEdgeInsetsMake(0, _publisherTask.titleLabel.bounds.size.width+5, 0, -_publisherTask.titleLabel.bounds.size.width)];
        [_publisherTask setImage:Image(@"triangle_down") forState:UIControlStateNormal];
    }
    return _publisherTask;
}

- (void)addline:(UIButton *)button
{
    button.titleLabel.font = FONT(16);
    UIView *line = [[UIView alloc] init];
    if (button.tag == 1) {
        line.backgroundColor = [UIColor colorWithHexString:@"ff783c"];
    }
    line.backgroundColor = [UIColor colorWithHexString:@"cfcfcf"];
    line.tag = 11;
    [button addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
}

- (UIButton *)background
{
    if (!_background) {
//        _background = [[UIView alloc] initWithFrame:self.view.frame];
        _background = [[UIButton alloc] init];
        _background.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.03];
        _background.hidden = YES;
        [self.view addSubview:_background];
        [_background mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(TextField_RowHeight);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(IPHONE_W);
            make.height.mas_equalTo(IPHONE_H-49-64-TextField_RowHeight);
        }];
        [_background addTarget:self action:@selector(tapGesturedDetected) forControlEvents:UIControlEventTouchDown];
        [_background addTarget:self action:@selector(tapGesturedDetected) forControlEvents:UIControlEventTouchUpInside];
        [_background addTarget:self action:@selector(tapGesturedDetected) forControlEvents:UIControlEventTouchUpOutside];
        [self addAGesutreRecognizer:_background];
        
    }
    return _background;
}

- (void)touchecsBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}

- (void)addAGesutreRecognizer:(UIView *)view

{
    UILongPressGestureRecognizer *longPressReger = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesturedDetected)];
    longPressReger.minimumPressDuration = 2.0;
    
    [view addGestureRecognizer:longPressReger];
}

- (void)tapGesturedDetected
{
    if (self.background.hidden == NO) {
        [self setHiddenListView:YES];
    }
}

- (THReportView *)reportView
{
    if (!_reportView) {
        _reportView = [[THReportView alloc] init];
        _reportView.titlename = @"举报";
        _reportView.hidden = YES;
        _reportView.delegate = self;
        [[UIApplication sharedApplication].keyWindow addSubview:_reportView];
    }
    return _reportView;
}

- (NSMutableArray *)publishers
{
    if (!_publishers) {
        _publishers = [[NSMutableArray alloc] init];
    }
    return _publishers;
}

- (NSMutableArray *)tasks{
    if (!_tasks) {
        _tasks = [[NSMutableArray alloc] init];
    }
    return _tasks;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
